import datetime

from django.apps import apps
from unittest import TestResult, TextTestRunner
from django.test.runner import DiscoverRunner

from django_redis import get_redis_connection


class DjangoTestResult(TestResult):
    separator = '-' * 70

    def stopTest(self, test):
        """Called when the given test has been run"""
        self.testsRun += 1
        super(DjangoTestResult, self).stopTest(test)
        # if not hasattr(self, 'is_print'):
        #     doc = type(test).__doc__.strip()
        #     self.is_print = True
        #     a, b, c = doc.split('\n')
        # print(self.separator)
        # print(f"1、测试案例1-1，测试人员：蔡伟,模块/功能：" + a.strip())
        # print("    输入条件：" + b.strip())
        # print("    预计输出：" + c.strip())
        # print("    实际输出：符合")
        # print("    测试截图：")

    def stopTestRun(self):
        conn = get_redis_connection('users')
        conn.flushall()
        conn.close()
        print(f"Passed {self.testsRun} tests")

    def startTest(self, test):
        setattr(test, "startTime", datetime.datetime.now())

    def printErrors(self):
        self.print_error_list('ERROR', self.errors)
        self.print_error_list('FAIL', self.failures)

    def print_error_list(self, flavour, errors):
        for test, err in errors:
            print(self.separator)
            print("%s: %s" % (flavour, self.get_description(test)))
            print(self.separator)
            print("%s" % err)

    def get_description(self, test):
        doc_first_line = test.shortDescription()
        if doc_first_line:
            return '\n'.join((str(test), doc_first_line))
        else:
            return str(test)


class DjangoTextTestRunner(TextTestRunner):
    resultclass = DjangoTestResult


class DjangoTestRunner(DiscoverRunner):
    """
    Test runner that automatically makes all unmanaged models in your Django
    project managed for the duration of the test run, so that one doesn't need
    to execute the SQL manually to create them.
    """

    test_runner = DjangoTextTestRunner

    def setup_test_environment(self, *args, **kwargs):
        self.unmanaged_models = [m for m in apps.get_models()]
        for m in self.unmanaged_models:
            m._meta.managed = True
        super(DjangoTestRunner, self).setup_test_environment(**kwargs)

    def teardown_test_environment(self, *args, **kwargs):
        super(DjangoTestRunner, self).teardown_test_environment(**kwargs)
        # reset unmanaged models
        for m in self.unmanaged_models:
            m._meta.managed = False
